package com.mxf.code.product_coupon.strategy.impl;

import com.mxf.code.product_coupon.domain.FullReduction;
import com.mxf.code.product_coupon.domain.FullReductionItem;
import com.mxf.code.product_coupon.domain.Product;
import com.mxf.code.product_coupon.strategy.FullReductionStrategy;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 类型满减策略
 *
 * @author 28382
 */
public class FullReductionForTypeStrategy implements FullReductionStrategy {

    @Override
    public BigDecimal calculateFullReductionPrice(List<Product> productList) {
        BigDecimal total = BigDecimal.ZERO;

        Map<String, List<Product>> productMap = productList.stream()
                .collect(Collectors.groupingBy(Product::getType));

        for (Map.Entry<String, List<Product>> entry : productMap.entrySet()) {
            String productType = entry.getKey();
            List<Product> products = entry.getValue();

            BigDecimal totalProductPrice = products.stream()
                    .map(Product::getPrice)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            if (FullReduction.FULL_REDUCTION_BY_PRODUCT_TYPE_MAP.containsKey(productType)) {
                List<FullReductionItem> fullReductionItems = FullReduction.FULL_REDUCTION_BY_PRODUCT_TYPE_MAP.get(productType);
                BigDecimal maxReduction = BigDecimal.ZERO;
                for (FullReductionItem item : fullReductionItems) {
                    if (totalProductPrice.compareTo(item.getThreshold()) >= 0 && item.getReduction().compareTo(maxReduction) > 0) {
                        maxReduction = item.getReduction();
                    }
                }
                total = total.add(totalProductPrice.subtract(maxReduction));
            } else {
                total = total.add(totalProductPrice);
            }
        }

        return total;
    }

}
